<?php

/**
 * This is the model class for table "{{clients}}".
 *
 * The followings are the available columns in table '{{clients}}':
 * @property integer $id
 * @property string $surname
 * @property string $name
 * @property string $patronymic
 * @property string $dob
 * @property string $phone
 * @property string $email
 * @property string $created_at
 * @property string $updated_at
 * @property integer $active
 */
class Clients extends CActiveRecord
{
	public $fio;
	public $birthplace;
	public $prev_passport = true;

	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Clients the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{clients}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('surname, name, patronymic, dob, created_at', 'required'),
			array('active', 'numerical', 'integerOnly'=>true),
			array('surname, name, patronymic', 'length', 'max'=>250),
			array('dob','date','format'=>'yyyy-MM-dd'),
			array('phone', 'length', 'max'=>30),
			array('email', 'email'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, surname, name, patronymic, dob, phone, email, created_at, updated_at, active', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'credits'=>array(self::HAS_MANY,'Credits','client_id'),
			'reg_address'=>array(self::HAS_ONE,'Addresses','client_id','condition'=>'type='.Addresses::TYPE_REGISTRATION),
			'hab_address'=>array(self::HAS_ONE,'Addresses','client_id','condition'=>'type='.Addresses::TYPE_HABITATION),
			'passports'=>array(self::HAS_MANY,'Passports','client_id')
		);
	}

	public function behaviors(){
		return array(
			'createUpdateBehavior' => array(
				'class' => 'application.behaviors.CreateDateBehavior',
				'createdField' => 'created_at'
			)
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'surname' => 'Фамилия',
			'name' => 'Имя',
			'patronymic' => 'Отчество',
			'dob' => 'Дата рождения',
			'phone' => 'Телефон',
			'email' => 'Email',
			'created_at' => 'Создан',
			'updated_at' => 'Обновлен',
			'active' => 'Active',
		);
	}

	public function beforeValidate()
	{
		parent::beforeValidate();
		$this->dob = trim($this->dob)?date('Y-m-d',strtotime($this->dob)):'';
		return true;
	}

	public function afterFind()
	{
		parent::afterFind();

		$this->fio = $this->surname.' '.$this->name.' '.$this->patronymic;



		return true;
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria = new CDbCriteria;

		$criteria->select = '*, CONCAT_WS(" ",surname,name,patronymic) AS fio';
		$criteria->compare('CONCAT_WS(" ",surname,name,patronymic)',$this->fio,true);
		if($this->dob)
			$criteria->compare('dob',date('Y-m-d',strtotime($this->dob)));

		if(Yii::app()->user->getState('role')==Users::MANAGER_ROLE){
			$criteria->addInCondition('id',$this->_getClientsList());
		}

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
			'sort'=>array(
				'defaultOrder'=>'fio',
				'attributes'=>array(
					'fio'=>array(
						'asc'=>'surname',
						'desc'=>'surname DESC',
					),
					'*',
				),

			),
			'pagination'=>array(
				'pageSize'=>20,
			),
		));
	}

	private function _getClientsList()
	{
		$in_array = array();
		$organization_shops = Shops::model()->with('credits')->together(true)->findAll('t.organization_id = :oid',array(':oid'=>Yii::app()->user->getState('organization_id')));

		if(!empty($organization_shops)){
			foreach($organization_shops as $shop){
				foreach($shop->credits as $credit){
					$in_array[] = $credit->client_id;
				}
			}
		}

		return array_unique($in_array);
	}

	public function getCurrentPassport()
	{
		$criteria = new CDbCriteria();
		$criteria->compare('client_id',$this->id);
		$criteria->compare('type',Passports::TYPE_CURRENT);

		return Passports::model()->find($criteria);
	}

	public function getPrevPassport()
	{
		$criteria = new CDbCriteria();
		$criteria->compare('client_id',$this->id);
		$criteria->compare('type',Passports::TYPE_PREV);

		return Passports::model()->find($criteria);
	}
}